package com.xx.service.impl;

import com.xx.bean.Book;
import com.xx.mapper.BookMapper;
import com.xx.service.BookService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class BookServiceImpl implements BookService {
    public static BookMapper getSqlSession() throws IOException {
        String resource = "mybatis-config.xml";
        //读取类路径下的配置文件得到输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象，相当于Connection对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession.getMapper(BookMapper.class);
    }


    @Override
    public List selectBooks() {
        try {
            BookMapper mapper = getSqlSession();
            List<Book> books = mapper.listBook();
            return books;
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public void removeBookById(Integer id) throws Exception {
        BookMapper mapper = getSqlSession();
        mapper.deleteBook(id);
    }

    @Override
    public void addBook(Book book) throws Exception{
        BookMapper mapper = getSqlSession();
        mapper.insertBook(book);
    }

}
